# In[1]:
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

import simpy

# In[2]:
from pylab import mpl
# 指定默认字体：解决plot不能显示中文问题
mpl.rcParams['font.sans-serif'] = ['SimHei'] 
# 解决保存图像是负号'-'显示为方块的问题
mpl.rcParams['axes.unicode_minus'] = False 

# In[3]:
from AirportSimulator import *
from Airplane import *

# In[8]:
RANDOM_SEED = 42

AVERAGE_ARRIVIAL_TIME = 2 * 60

NUM_RUNWAY = 1
NUM_PARKING_BAY = 42
NUM_GROUND_SERVICE_GROUP = 35

NUM_CUSTOMER = int(
    float(60 * 60) / AVERAGE_ARRIVIAL_TIME)

# In[9]:
random.seed(RANDOM_SEED)
env = simpy.Environment()
simAirPort = AirportSimulator(
    env, 
    num_customer=NUM_CUSTOMER,
    average_arrival_time=AVERAGE_ARRIVIAL_TIME,
    num_runways=NUM_RUNWAY,
    num_parking_bays=NUM_PARKING_BAY,
    num_ground_services_groups=NUM_GROUND_SERVICE_GROUP,
    record_queue_len=True
)

# In[10]:
env.run()

# In[11]:
res_data = simAirPort.result
res_data['landing_wait_time'].mean()

# In[14]:
fig, ax = plt.subplots(dpi=300)
sns.histplot(
    res_data['landing_wait_time'] / 60,
    bins=20,
    kde=True,
    ax=ax)
ax.set_title(
    '航班到达率为' + str(
        AVERAGE_ARRIVIAL_TIME
        ) + 's/架次时着陆等待时间分布情况'
    )
ax.set_xlabel('等待时间（分钟）')
ax.set_ylabel('计数')

# In[15]:
queue_len_df = simAirPort.queue_len_df
queue_len_df['runways'].mean()

# In[16]:
fig, ax = plt.subplots(dpi=300)
queue_len_df = simAirPort.queue_len_df
queue_len_df[[
    'runways',
    'parking_bays',
    'ground_services_groups'
    ]].plot(ax=ax)
ax.set_title(
    '航班到达率为' + str(
        AVERAGE_ARRIVIAL_TIME
        ) + 's/架次时等待着陆排队情况'
    )

# In[7]:
is_delayed_list = []
for i in range(len(res_data)):
    if res_data.iloc[i, 3] > (20 * 60):
        is_delayed_list.append(1)
    else:
        is_delayed_list.append(0)
        
res_data['is_delayed'] = is_delayed_list
print(
      '延误率为', 
      (len(res_data[res_data['is_delayed'] == 1]) / len(res_data))
      )